<template>
  <div class="app-store-container">
    <el-card>
      <div slot="header">
        <span>应用商店</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="fetchAppList">
          <i class="el-icon-refresh"></i> 刷新
        </el-button>
      </div>
      
      <div v-loading="loading">
        <el-tabs type="border-card">
          <el-tab-pane v-for="(apps, category) in groupedApps" :key="category" :label="getCategoryName(category)">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="app in apps" :key="app.id">
                <el-card shadow="hover" class="app-card">
                  <div class="app-icon">
                    <i :class="getAppIcon(app.category)"></i>
                  </div>
                  
                  <div class="app-info">
                    <h3>{{ app.name }}</h3>
                    <p class="app-description">{{ app.description }}</p>
                    
                    <div class="app-status">
                      <el-tag v-if="app.installed" type="success">已安装</el-tag>
                      <el-tag v-else type="info">未安装</el-tag>
                      
                      <el-tag v-if="app.installed && app.running" type="success">运行中</el-tag>
                      <el-tag v-if="app.installed && !app.running" type="danger">已停止</el-tag>
                    </div>
                    
                    <div class="app-actions">
                      <el-button 
                        v-if="!app.installed" 
                        type="primary" 
                        size="mini" 
                        @click="handleInstall(app)"
                        :disabled="!isAdmin">
                        安装
                      </el-button>
                      
                      <template v-else>
                        <el-button 
                          type="success" 
                          size="mini" 
                          @click="handleAction(app, 'start')"
                          :disabled="app.running || !isAdmin">
                          启动
                        </el-button>
                        
                        <el-button 
                          type="warning" 
                          size="mini" 
                          @click="handleAction(app, 'stop')"
                          :disabled="!app.running || !isAdmin">
                          停止
                        </el-button>
                        
                        <el-button 
                          type="danger" 
                          size="mini" 
                          @click="handleUninstall(app)"
                          :disabled="!isAdmin">
                          卸载
                        </el-button>
                      </template>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
    
    <!-- 详情对话框 -->
    <el-dialog :title="currentApp ? currentApp.name + ' 详情' : '应用详情'" :visible.sync="dialogVisible" width="600px">
      <div v-if="currentApp" class="app-detail">
        <div class="detail-section">
          <table class="detail-table">
            <tr>
              <td class="detail-label">名称:</td>
              <td class="detail-content">{{ currentApp.name }}</td>
              <td class="detail-label">状态:</td>
              <td class="detail-content">
                <el-tag v-if="currentApp.installed" type="success">已安装</el-tag>
                <el-tag v-else type="info">未安装</el-tag>
              </td>
            </tr>
            <tr>
              <td class="detail-label">描述:</td>
              <td class="detail-content" colspan="3">{{ currentApp.description }}</td>
            </tr>
            <tr v-if="currentApp.installed">
              <td class="detail-label">版本:</td>
              <td class="detail-content">{{ currentApp.version || '未知' }}</td>
              <td class="detail-label">运行状态:</td>
              <td class="detail-content">
                <el-tag v-if="currentApp.running" type="success">运行中</el-tag>
                <el-tag v-else type="danger">已停止</el-tag>
              </td>
            </tr>
            <tr>
              <td class="detail-label">端口:</td>
              <td class="detail-content" colspan="3">
                <span v-if="currentApp.ports && currentApp.ports.length">
                  {{ currentApp.ports.join(', ') }}
                </span>
                <span v-else>-</span>
              </td>
            </tr>
            <tr>
              <td class="detail-label">配置文件:</td>
              <td class="detail-content" colspan="3">
                <div v-if="currentApp.configFiles && currentApp.configFiles.length">
                  <div v-for="(file, index) in currentApp.configFiles" :key="index">
                    {{ file }}
                  </div>
                </div>
                <span v-else>-</span>
              </td>
            </tr>
            <tr>
              <td class="detail-label">数据目录:</td>
              <td class="detail-content" colspan="3">
                <div v-if="currentApp.dataDir && currentApp.dataDir.length">
                  <div v-for="(dir, index) in currentApp.dataDir" :key="index">
                    {{ dir }}
                  </div>
                </div>
                <span v-else>-</span>
              </td>
            </tr>
          </table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { mockApps } from '@/utils/mock'

export default {
  name: 'AppStore',
  data() {
    return {
      loading: true,
      appList: [],
      groupedApps: {},
      dialogVisible: false,
      currentApp: null,
      useMockData: true // 在后端API准备好前使用模拟数据
    }
  },
  computed: {
    ...mapGetters([
      'isAdmin'
    ])
  },
  created() {
    this.fetchAppList()
  },
  methods: {
    // 获取应用列表
    fetchAppList() {
      this.loading = true
      
      if (this.useMockData) {
        // 使用模拟数据
        this.groupedApps = mockApps
        this.loading = false
      } else {
        // 使用实际API
        this.$http.get('/app/list')
          .then(res => {
            this.groupedApps = res.data
            this.loading = false
          })
          .catch(error => {
            this.$message.error(error.response?.data?.error || '获取应用列表失败')
            this.loading = false
            // 如果API调用失败，切换到模拟数据
            this.useMockData = true
            this.fetchAppList()
          })
      }
    },
    
    // 安装应用
    handleInstall(app) {
      if (!this.isAdmin) {
        this.$message.warning('需要管理员权限进行此操作')
        return
      }
      
      this.$confirm(`确定要安装 ${app.name} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        
        if (this.useMockData) {
          // 模拟安装操作
          setTimeout(() => {
            // 更新模拟数据状态
            app.installed = true
            app.running = true
            this.$message.success(`${app.name} 安装成功`)
            this.loading = false
          }, 1000)
        } else {
          // 使用实际API
          this.$http.post(`/app/install/${app.id}`)
            .then(() => {
              this.$message.success(`${app.name} 安装成功`)
              this.fetchAppList()
            })
            .catch(error => {
              this.$message.error(error.response?.data?.error || '安装失败')
              this.loading = false
            })
        }
      }).catch(() => {})
    },
    
    // 卸载应用
    handleUninstall(app) {
      if (!this.isAdmin) {
        this.$message.warning('需要管理员权限进行此操作')
        return
      }
      
      this.$confirm(`确定要卸载 ${app.name} 吗? 这可能会导致依赖此应用的服务无法正常运行。`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        
        if (this.useMockData) {
          // 模拟卸载操作
          setTimeout(() => {
            // 更新模拟数据状态
            app.installed = false
            app.running = false
            this.$message.success(`${app.name} 卸载成功`)
            this.loading = false
          }, 1000)
        } else {
          // 使用实际API
          this.$http.post(`/app/uninstall/${app.id}`)
            .then(() => {
              this.$message.success(`${app.name} 卸载成功`)
              this.fetchAppList()
            })
            .catch(error => {
              this.$message.error(error.response?.data?.error || '卸载失败')
              this.loading = false
            })
        }
      }).catch(() => {})
    },
    
    // 应用操作（启动/停止）
    handleAction(app, action) {
      if (!this.isAdmin) {
        this.$message.warning('需要管理员权限进行此操作')
        return
      }
      
      this.$confirm(`确定要${action === 'start' ? '启动' : '停止'} ${app.name} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        
        if (this.useMockData) {
          // 模拟操作
          setTimeout(() => {
            // 更新模拟数据状态
            app.running = action === 'start'
            this.$message.success(`${app.name} ${action === 'start' ? '已启动' : '已停止'}`)
            this.loading = false
          }, 1000)
        } else {
          // 使用实际API
          this.$http.post(`/app/action/${app.id}`, { action })
            .then(() => {
              this.$message.success(`${app.name} ${action === 'start' ? '已启动' : '已停止'}`)
              this.fetchAppList()
            })
            .catch(error => {
              this.$message.error(error.response?.data?.error || '操作失败')
              this.loading = false
            })
        }
      }).catch(() => {})
    },
    
    // 查看应用详情
    handleViewDetail(app) {
      this.currentApp = null
      this.loading = true
      
      if (this.useMockData) {
        // 模拟获取详情
        setTimeout(() => {
          this.currentApp = {
            ...app,
            ports: app.id === 'nginx' ? [80, 443] : 
                   app.id === 'mysql' ? [3306] : 
                   app.id === 'redis' ? [6379] : [],
            configFiles: app.id === 'nginx' ? ['/etc/nginx/nginx.conf'] : 
                         app.id === 'mysql' ? ['/etc/mysql/my.cnf'] : 
                         app.id === 'redis' ? ['/etc/redis/redis.conf'] : [],
            dataDir: app.id === 'nginx' ? ['/var/www/html'] : 
                     app.id === 'mysql' ? ['/var/lib/mysql'] : 
                     app.id === 'redis' ? ['/var/lib/redis'] : []
          }
          this.dialogVisible = true
          this.loading = false
        }, 500)
      } else {
        // 使用实际API
        this.$http.get(`/app/info/${app.id}`)
          .then(res => {
            this.currentApp = res.data
            this.dialogVisible = true
            this.loading = false
          })
          .catch(error => {
            this.$message.error(error.response?.data?.error || '获取应用详情失败')
            this.loading = false
          })
      }
    },
    
    // 获取分类名称
    getCategoryName(category) {
      const categories = {
        web: 'Web服务器',
        database: '数据库',
        language: '编程语言',
        cache: '缓存和队列',
        security: '安全工具',
        other: '其他应用'
      }
      
      return categories[category] || category
    },
    
    // 获取应用图标
    getAppIcon(category) {
      const icons = {
        web: 'el-icon-s-platform',
        database: 'el-icon-s-management',
        language: 'el-icon-s-opportunity',
        cache: 'el-icon-s-cooperation',
        security: 'el-icon-s-claim',
        other: 'el-icon-s-grid'
      }
      
      return icons[category] || 'el-icon-s-grid'
    }
  }
}
</script>

<style scoped>
.app-card {
  margin-bottom: 20px;
  height: 220px;
  display: flex;
  flex-direction: column;
}

.app-icon {
  font-size: 36px;
  color: #409EFF;
  text-align: center;
  margin: 10px 0;
}

.app-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.app-info h3 {
  margin: 5px 0;
  font-size: 16px;
  text-align: center;
}

.app-description {
  flex: 1;
  margin: 5px 0;
  font-size: 12px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.app-status {
  margin: 5px 0;
  display: flex;
  justify-content: space-around;
}

.app-actions {
  margin-top: 10px;
  display: flex;
  justify-content: space-around;
}

.app-detail {
  max-height: 500px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
}

.detail-label {
  width: 25%;
  font-weight: bold;
  padding: 12px;
  color: #606266;
  background-color: #F5F7FA;
  border: 1px solid #EBEEF5;
}

.detail-content {
  width: 25%;
  padding: 12px;
  color: #606266;
  border: 1px solid #EBEEF5;
}
</style> 